package com.lanyeo.liver.ui

import android.content.Context
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.view.WindowManager.LayoutParams
import android.widget.AdapterView
import android.widget.Button
import android.widget.Toast
import com.lanyeo.liver.R
import com.lanyeo.liver.databinding.ControlPanelBinding
import com.lanyeo.liver.task.TaskFishing
import com.lanyeo.liver.task.ITask
import com.lanyeo.liver.task.TaskMaking
import com.lanyeo.liver.task.TaskResource
import com.lanyeo.liver.task.TaskHunt
import com.lanyeo.liver.task.TaskLockAnimal
import kotlin.math.min

class ControlPanel(context:Context) {
    private data class DataTask(val iTask: ITask, val iSetting: ISetting)
    private var btnFlow: Button = Button(context)
    private var btnFlowExists = true
    private var panel:View
    private var windowManager: WindowManager = context.getSystemService(WindowManager::class.java)
    private var windowParams: LayoutParams
    private var _binding: ControlPanelBinding? = null
    private val binding get() = _binding!!
    private var screenWidth: Int = 0
    private var screenHeight: Int = 0
    private var onScriptClickListener:OnScriptClickListener? = null
    private var onTaskTouchListener:ITask.OnTaskTouchListener? = null
    private var onButtonFlowHideListener: OnButtonFlowHideListener? = null
    private val tasks = mapOf(Pair(context.resources.getStringArray(R.array.tasks)[0], DataTask(TaskFishing(context), SettingFinishing(context))),
        Pair(context.resources.getStringArray(R.array.tasks)[1], DataTask(TaskResource(context), SettingResource(context))),
        Pair(context.resources.getStringArray(R.array.tasks)[2], DataTask(TaskMaking(context), SettingMaking(context))),
        Pair(context.resources.getStringArray(R.array.tasks)[3], DataTask(TaskHunt(context), SettingHunt(context))),
        Pair(context.resources.getStringArray(R.array.tasks)[4], DataTask(TaskLockAnimal(context), SettingLockAnimal(context)))
    )
    private var currentTask: ITask? = null
    private var currentTaskSetting: ISetting? = null
    private var taskRunning: Boolean = false
    init {
        screenWidth = windowManager.maximumWindowMetrics.bounds.width()
        screenHeight = windowManager.maximumWindowMetrics.bounds.height()
        val minWidth = min(screenWidth, screenHeight)
        val flowButtonSize = minWidth / 10
        btnFlow.setBackgroundResource(R.mipmap.ic_launcher)
        btnFlow.maxWidth = flowButtonSize
        btnFlow.maxHeight = flowButtonSize
        btnFlow.background.alpha = 255

        _binding = ControlPanelBinding.inflate(LayoutInflater.from(context))
        panel = binding.root

        windowParams = LayoutParams()
        windowParams.x = 5
        windowParams.y = 85
        windowParams.type = LayoutParams.TYPE_APPLICATION_OVERLAY
        windowParams.flags = windowParams.flags or LayoutParams.FLAG_NOT_FOCUSABLE
        windowParams.gravity = Gravity.START or Gravity.TOP
        windowParams.width = flowButtonSize
        windowParams.height = flowButtonSize
        windowManager.addView(btnFlow, windowParams)

        val panelWidth = minWidth / 2
        val panelHeight = panelWidth * 3 / 4
        // 短按显示任务设置窗口
        btnFlow.setOnClickListener {
            windowManager.removeView(btnFlow)
            windowParams.width = panelWidth
            windowParams.height = panelHeight
            windowManager.addView(panel, windowParams)
        }

        // 长按隐藏悬浮按钮
        btnFlow.setOnLongClickListener {
            windowManager.removeView(btnFlow)
            onButtonFlowHideListener?.click()
            btnFlowExists = false
            return@setOnLongClickListener true
        }

        // 隐藏任务设置面板
        binding.btnHide.setOnClickListener {
            windowManager.removeView(panel)
            windowParams.width = flowButtonSize
            windowParams.height = flowButtonSize
            windowManager.addView(btnFlow, windowParams)
        }

        // 开始任务按钮
        binding.btnStartScript.setOnClickListener {
            if (currentTask == null) {
                taskRunning = false
                return@setOnClickListener
            }
            if (taskRunning) {
                onScriptClickListener?.click(null)
                currentTask?.finishTask()
            } else {
                currentTask?.initTask(onTaskTouchListener, currentTaskSetting!!.params())
                onScriptClickListener?.click(currentTask)
            }
            taskRunning = !taskRunning
            binding.btnStartScript.setImageResource(if (!taskRunning) R.drawable.start else R.drawable.pause)
        }

        // 选择任务的设置面板
        binding.spScipt.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                val taskName = parent!!.getItemAtPosition(position).toString()
                Log.d(TAG, "pos: $position id:$id task:$taskName")
                if (!taskRunning) {
                    currentTask = tasks[taskName]!!.iTask
                    if (currentTaskSetting != null) {
                        binding.taskSettingLayout.removeView(currentTaskSetting!!.view())
                    }
                    currentTaskSetting = tasks[taskName]!!.iSetting
                    binding.taskSettingLayout.addView(currentTaskSetting!!.view())
                } else {
                    Toast.makeText(context, R.string.need_stop_script, Toast.LENGTH_SHORT).show()
                }
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {
                Log.d(TAG, "onNothingSelected")
            }
        }
    }

    fun setScriptClickListener(onScriptClickListener:OnScriptClickListener) {
        this.onScriptClickListener = onScriptClickListener
    }

    fun setTaskTouchListener(onTaskTouchListener: ITask.OnTaskTouchListener) {
        this.onTaskTouchListener = onTaskTouchListener
    }

    fun setButtonFlowHideListener(buttonFlowHideListener: OnButtonFlowHideListener) {
        this.onButtonFlowHideListener = buttonFlowHideListener
    }

    fun forceStopTask() {
        taskRunning = false
        currentTask?.finishTask()
        binding.btnStartScript.setImageResource(R.drawable.start)
    }

    fun reinit() {
        if (!btnFlowExists) {
            windowManager.addView(btnFlow, windowParams)
        }
        btnFlowExists = true
    }

    interface OnScriptClickListener {
        /**
         * @param task 当前要启动的task, 如果为null表示停止
         */
        fun click(task: ITask?)
    }

    /**
     * 监听浮动窗口隐藏事件
     */
    interface OnButtonFlowHideListener {
        fun click()
    }

    companion object {
        const val TAG = "ControlPanel"
    }
}